﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Net.Sgoliver.NRtfTree.Core;

namespace DeskNotes.Utils
{
    /// <summary>
    /// Converts plain text to rtf and rtf to plain text.
    /// </summary>
    public static class RtfConverter
    {
        internal static string RTF_TAG = "{\\rtf1\\";
        private static RichTextBox box;

        internal static RichTextBox TheBox
        {
            set
            {
                box = value;
            }
            get
            {
                return box;
            }
        }

        /// <summary>
        /// Converts rtf formatted text to plain text and return it.
        /// Required by non UI threads where RichTextBox cannot be used!
        /// </summary>
        /// <param name="rtf">RTF formatted string</param>
        /// <returns>plain text</returns>
        internal static string TextForBackground(string rtf)
        {
            string text;
            if (rtf.StartsWith(RTF_TAG))
            {
                RtfTree converter = new RtfTree();
                converter.LoadRtfText(rtf);
                text = converter.Text;
                converter = null;
            }
            else
                text = rtf;
            return text;
        }
        /// <summary>
        /// Converts rtf formatted text to plain text and return it.
        /// Use for calls from UI thread
        /// </summary>
        /// <param name="rtf">RTF formatted string</param>
        /// <returns>plain text</returns>
        internal static string Text(string rtf)
        {
            string text;
            if (rtf.StartsWith(RTF_TAG))
            {
                //RichTextBox box = new RichTextBox();
                box.Rtf = rtf;
                text = box.Text;
                //box.Dispose();
            }
            else
                text = rtf;
            return text;
        }
        /// <summary>
        /// Converts plain text into RTF and returns RTF formatted text.
        /// Use for calls from UI thread.
        /// </summary>
        /// <param name="text">Plain text</param>
        /// <returns>RTF formatted string</returns>
        public static string Rtf(string text)
        {
            string rtf;

            if (text.StartsWith(RTF_TAG))
                rtf = text;
            else
            {
                box.Text = text;
                rtf = box.Rtf;
            }
            return rtf;
        }
    }
}
